<template>
  <div class="params">
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片式图 -->
    <el-card>
      <el-alert
        title="注意：只允许为第三级分类设置相关参数"
        type="warning"
        show-icon
        :closable="false"
      >
      </el-alert>

      <!-- 选择商品分类  -->
      <el-row>
        <el-col :span="10">
          选择商品分类 :
          <el-cascader
            v-model="selectedKeys"
            :options="allCateList"
            :props="allCateListProps"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>

      <!-- tab页签区域 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <!-- 动态参数面板 -->
        <el-tab-pane label="动态参数" name="many">
          <el-row>
            <el-col>
              <el-button
                type="primary"
                :disabled="isBtnDisabled"
                @click="addFormVisible = true"
              >
                添加参数
              </el-button>
              <!-- 动态参数表格 -->
              <el-table :data="manyTableData" style="width: 100%" border stripe>
                <!-- 展开行 -->
                <el-table-column type="expand" width="50">
                  <template slot-scope="scope">
                    <el-tag
                      v-for="(item, index) in scope.row.attr_vals"
                      :key="index"
                      closable
                      @close="deleteTag(index, scope.row)"
                      >{{ item }}</el-tag
                    >
                    <el-input
                      class="input-new-tag"
                      v-if="scope.row.inputVisible"
                      v-model="scope.row.inputValue"
                      ref="saveTagInput"
                      size="small"
                      @keyup.enter.native="handleInputConfirm(scope.row)"
                      @blur="handleInputCancel(scope.row)"
                    >
                    </el-input>
                    <el-button v-else size="small" @click="showInput(scope.row)"
                      >+ New Tag</el-button
                    >
                  </template>
                </el-table-column>

                <el-table-column type="index" width="50"></el-table-column>
                <el-table-column prop="attr_name" label="参数名称">
                </el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <el-button
                      type="primary"
                      icon="el-icon-edit"
                      size="mini"
                      @click="showEditParams(scope.row.attr_id)"
                      >编辑</el-button
                    >
                    <el-button
                      type="danger"
                      icon="el-icon-delete"
                      size="mini"
                      @click="delParams(scope.row.attr_id)"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-row>
        </el-tab-pane>
        <!-- 静态属性面板 -->
        <el-tab-pane label="静态属性" name="only">
          <el-row>
            <el-col>
              <el-button
                type="primary"
                :disabled="isBtnDisabled"
                @click="addFormVisible = true"
              >
                添加属性
              </el-button>
              <!-- 静态属性表格 -->
              <el-table :data="onlyTableData" style="width: 100%" border stripe>
                <!-- 展开行 -->
                <el-table-column type="expand" width="50">
                  <template slot-scope="scope">
                    <el-tag
                      v-for="(item, index) in scope.row.attr_vals"
                      :key="index"
                      closable
                      @close="deleteTag(index, scope.row)"
                      >{{ item }}</el-tag
                    >
                    <el-input
                      class="input-new-tag"
                      v-if="scope.row.inputVisible"
                      v-model="scope.row.inputValue"
                      ref="saveTagInput"
                      size="small"
                      @keyup.enter.native="handleInputConfirm(scope.row)"
                      @blur="handleInputCancel(scope.row)"
                    >
                    </el-input>
                    <el-button v-else size="small" @click="showInput(scope.row)"
                      >+ New Tag</el-button
                    >
                  </template>
                </el-table-column>

                <el-table-column type="index" width="50"></el-table-column>
                <el-table-column prop="attr_name" label="参数名称">
                </el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <el-button
                      type="primary"
                      icon="el-icon-edit"
                      size="mini"
                      @click="showEditParams(scope.row.attr_id)"
                      >编辑</el-button
                    >
                    <el-button
                      type="danger"
                      icon="el-icon-delete"
                      size="mini"
                      @click="delParams(scope.row.attr_id)"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加参数属性的对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addFormVisible"
      width="50%"
      @close="resetForm"
    >
      <el-form :model="addForm" :rules="rules" ref="FormRef">
        <el-form-item
          :label="titleText"
          :label-width="formLabelWidth"
          prop="attr_name"
        >
          <el-input v-model="addForm.attr_name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 修改参数的对话框 -->
    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="editFormVisible"
      width="50%"
      @close="resetForm"
    >
      <el-form :model="editForm" :rules="rules" ref="FormRef">
        <el-form-item
          :label="titleText"
          :label-width="formLabelWidth"
          prop="attr_name"
        >
          <el-input v-model="editForm.attr_name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      allCateList: [], //商品分类的数据列表，默认为空
      allCateListProps: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      selectedKeys: [], //选中分类对应所有的id值的数组
      id: "", //三级分类对应的id
      activeName: "many", //被激活页签的id
      manyTableData: [], //动态参数列表
      onlyTableData: [], //静态属性列表
      addFormVisible: false, //控制添加参数属性对话框的显示隐藏
      formLabelWidth: "80px",
      addForm: {
        attr_name: "",
      },
      editFormVisible: false, //控制修改参数属性对话框的显示隐藏
      editForm: {}, //修改参数对话框的表单
      inputVisible: false, //控制按钮与文本框的切换显示
      inputValue: "", //文本框中输入的内容
      rules: {
        attr_name: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
        ],
      },
    };
  },
  mounted() {
    this.getCateList();
  },
  methods: {
    //获取商品分类数据列表
    getCateList() {
      this.axios.get("categories").then((res) => {
        let result = res.data;
        if (result.meta.status !== 200) {
          return this.$message.error("获取商品分类失败");
        }
        this.allCateList = result.data;
      });
    },
    //监听选择分类的选中操作
    handleChange() {
      //判断选中的是否为三级分类
      if (this.selectedKeys.length !== 3) {
        this.selectedKeys = [];
        this.manyTableData = []; //动态参数列表
        this.onlyTableData = []; //静态属性列表
        return;
      } else if (this.selectedKeys.length === 3) {
        //获取三级分类对应的id
        this.id = this.selectedKeys[this.selectedKeys.length - 1];
        this.getParamsData();
      }
    },
    //tab页签的切换
    handleClick() {
      // console.log(this.activeName);
      if (this.id) {
        this.getParamsData();
      }
    },
    //动态获取参数属性table列表
    getParamsData() {
      this.axios
        .get(`categories/${this.id}/attributes`, {
          params: { sel: this.activeName },
        })
        .then((res) => {
          let result = res.data;
          if (result.meta.status !== 200) {
            return this.$message.error("获取参数属性失败");
          }
          // console.log(result.data);
          result.data.forEach((item) => {
            item.attr_vals = item.attr_vals ? item.attr_vals.split(",") : [];
            //控制文本框的显示与隐藏
            item.inputVisible = false;
            //文本框中输入的内容
            item.inputValue = "";
          });
          if (this.activeName == "many") {
            this.manyTableData = result.data;
          } else if (this.activeName == "only") {
            this.onlyTableData = result.data;
          }
          console.log(this.manyTableData);
        });
    },
    //dialog关闭后重置form表单
    resetForm() {
      this.$refs.FormRef.resetFields();
    },
    //添加参数属性
    addParams() {
      this.$refs.FormRef.validate((valid) => {
        if (!valid) {
          return this.$message.error("请认真填写必填项");
        }
        this.axios
          .post(`categories/${this.id}/attributes`, {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName,
          })
          .then((res) => {
            let result = res.data;
            if (result.meta.status !== 201) {
              return this.$message.error("创建失败");
            }
            this.$message.success("创建成功");
            this.addFormVisible = false;
            this.getParamsData();
          });
      });
    },
    //显示修改参数对话框
    showEditParams(attr_id) {
      this.editFormVisible = true;
      this.axios
        .get(`categories/${this.id}/attributes/${attr_id}`, {
          params: {
            attr_sel: this.activeName,
          },
        })
        .then((res) => {
          let result = res.data;
          console.log(result);
          if (result.meta.status !== 200) {
            return this.$message.error("获取参数信息失败");
          }
          this.editForm = result.data;
        });
    },
    // 提交修改参数属性
    editParams() {
      console.log(this.id);
      console.log(this.editForm);
      this.axios
        .put(`categories/${this.id}/attributes/${this.editForm.attr_id}`, {
          attr_name: this.editForm.attr_name,
          attr_sel: this.activeName,
        })
        .then((res) => {
          let result = res.data;
          console.log(result);
          if (result.meta.status !== 200) {
            return this.$message.error("修改失败");
          }
          this.$message.success("修改成功");
          this.getParamsData();
          this.editFormVisible = false;
        });
    },
    //删除对应参数属性
    delParams(attr_id) {
      this.$confirm("此操作将永久删除该参数, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.axios
            .delete(`categories/${this.id}/attributes/${attr_id}`)
            .then((res) => {
              let result = res.data;
              if (result.meta.status !== 200) {
                return this.$message.error("删除参数失败");
              }
              this.getParamsData();
              this.$message({
                type: "success",
                message: "删除参数成功!",
              });
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //控制添加参数tag输入框的显示隐藏
    showInput(row) {
      row.inputVisible = true;
      //$nextTick方法的作用  就是当页上的元素被重新渲染后才执行回调函数的代码
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    //回车添加对应参数的tag
    handleInputConfirm(row) {
      row.inputVisible = false;
      // console.log(row.inputValue);
      row.attr_vals.push(row.inputValue.trim());
      // console.log(row);
      this.saveAttrVals(row);
      row.inputValue = "";
    },
    handleInputCancel(row) {
      row.inputVisible = false;
      row.inputValue = "";
    },
    //删除对应参数的tag
    deleteTag(index, row) {
      row.attr_vals.splice(index, 1);
      this.saveAttrVals(row);
    },
    //将对attr_vals 的操作，保存到数据库中
    saveAttrVals(row) {
      this.axios
        .put(`categories/${this.id}/attributes/${row.attr_id}`, {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(),
        })
        .then((res) => {
          let result = res.data;
          // console.log(result);
          if (result.meta.status !== 200) {
            return this.$message.error("参数修改失败");
          }
          this.$message.success("参数修改成功");
        });
    },
  },
  computed: {
    isBtnDisabled() {
      return this.selectedKeys.length !== 3;
    },
    //动态计算标题d文本
    titleText() {
      if (this.activeName == "many") {
        return "动态参数";
      } else if (this.activeName == "only") {
        return "静态属性";
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.params {
  .el-row {
    margin: 15px 0;
    text-align: left;
  }
  .el-tag {
    margin: 5px 10px;
  }
  .el-table {
    margin-top: 15px;
  }
  .input-new-tag,
  .el-button {
    width: 90px;
    margin-left: 10px;
  }
}
</style>